﻿using Avalonia;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using JMClient.Service;
using JMClient.Views;
using JMClient.Assets.ClientDesignConfig;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;

namespace JMClient;

sealed class Program
{
 
    // Initialization code. Don't use any Avalonia, third-party APIs or any
    // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
    // yet and stuff might break.
    // public static void Main(string[] args) => BuildAvaloniaApp()
    //     .StartWithClassicDesktopLifetime(args);
   //public static IHost Host { get; private set; }
   // public static HostConfig HostConfig { get; private set; }
    
    [STAThread]
    public static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += (s, e) =>
        {
            var ex = (Exception)e.ExceptionObject;
            Console.WriteLine($"未处理异常: {ex}");
            File.AppendAllText("crash.log", $"[Unhandled] {ex}\n");
        };

        TaskScheduler.UnobservedTaskException += (s, e) =>
        {
            Console.WriteLine($"任务异常: {e.Exception}");
            File.AppendAllText("crash.log", $"[Task] {e.Exception}\n");
            e.SetObserved();
        };
        
        try
        {
            
         // 检查是否处于设计模式
        bool isDesignMode = args.Any(arg => arg.Contains("designer", StringComparison.OrdinalIgnoreCase) || 
                                            arg.Contains("transport", StringComparison.OrdinalIgnoreCase));
        // 1. 读取 Host 配置文件
        // var configuration = new ConfigurationBuilder()
        //     .SetBasePath(Directory.GetCurrentDirectory())
        //     .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        //     .Build();

        // 如果需要环境特定配置，可以在这里添加
        // var environment = GetEnvironment(); // 自定义环境检测逻辑
        // if (environment != "Development")
        // {
        //     configuration = new ConfigurationBuilder()
        //         .SetBasePath(Directory.GetCurrentDirectory())
        //         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        //         .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
        //         .Build();
        // }

        // // 2. 绑定配置到 HostConfig 对象
        // HostConfig = new HostConfig();
        // configuration.Bind(HostConfig);

        // 调试输出：验证配置读取

        #region 记录配置内容文件

        // var programLogger = LogManagement.GetLogger<Program>(typeof(SystemLog));
        // programLogger.LogInformation("应用名称: {AppName}", HostConfig.Application.Name);
        // programLogger.LogInformation("应用版本: {Version}", HostConfig.Application.Version);
        // programLogger.LogInformation("运行环境: {Environment}", HostConfig.Application.Environment);
        // programLogger.LogInformation("默认日志级别: {DefaultLevel}", HostConfig.Logging.LogLevel.Default);
        // programLogger.LogInformation("Microsoft日志级别: {MicrosoftLevel}", HostConfig.Logging.LogLevel.Microsoft);
        // programLogger.LogInformation("数据库连接: {ConnectionString}", HostConfig.Database.ConnectionString);
        // programLogger.LogInformation("窗口标题: {Title}", HostConfig.Window.Title);

            #endregion

        /*
        // 3. 构建 Host
        Host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
            .ConfigureServices((context, services) =>
            {
                // 注册 Host 配置
                services.AddSingleton<HostConfig>(config =>
                {
                    return HostConfig;
                });
                
                //系统日志服务
                services.AddSingleton<SystemLog>(serviceProvider =>
                {
                    //工厂方法模式注册
                    var SystemLog = (SystemLog)LogManagement.RegisterLogInstance(typeof(SystemLog));
                    // 写启动日志
                    SystemLog.Write("程序启动，日志系统初始化成功", LogLevel.Information);
                    return SystemLog;
                });
                //系统配置服务
                services.AddSingleton<ConfigService>(serviceProvider =>
                {
                    var log = Program.Host.Services.GetRequiredService<SystemLog>();
                    var ConfigService = new ConfigService(log);
                    return ConfigService;
                });
                
            })
            .Build();*/
      

        // 启动 Avalonia 应用
        BuildAvaloniaApp()
            .StartWithClassicDesktopLifetime(args);
        }
        catch (Exception ex)
        {
            // 写入控制台
            Console.WriteLine($"程序崩溃: {ex}");

            // 如果你有 SystemLog 实例，可以写入日志
            var systemLog = LogManagement.GetLogger<Program>(typeof(SystemLog));
            systemLog.LogError(ex, "程序在 Main 方法中崩溃");

            // 可选：写入文件
            File.AppendAllText("crash.log", $"[{DateTime.Now}] {ex}\n");
        }

    }
    // Avalonia configuration, don't remove; also used by visual designer.
    public static AppBuilder BuildAvaloniaApp()
        => AppBuilder.Configure<App>()
            .UsePlatformDetect()
            .WithInterFont()
            .LogToTrace();
}